package org.wenhuayuan.project.main.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_profile.*
import org.wenhuayuan.library.resful.HiCallback
import org.wenhuayuan.library.resful.HiResponse
import org.wenhuayuan.library.util.HiDisplayUtil
import org.wenhuayuan.project.common.router.ARouterPath
import org.wenhuayuan.project.common.uicomp.HiBaseFragment
import org.wenhuayuan.project.common.view.loadCorner
import org.wenhuayuan.project.main.R
import org.wenhuayuan.project.main.biz.LoginActivity
import org.wenhuayuan.project.main.demo.DemoListActivity
import org.wenhuayuan.project.main.http.ApiFactory
import org.wenhuayuan.project.main.http.api.AccountApi
import org.wenhuayuan.project.main.model.CourseNotice
import org.wenhuayuan.project.main.model.Notice
import org.wenhuayuan.project.main.model.UserProfile
import org.wenhuayuan.uilibrary.banner.core.HiBannerAdapter
import org.wenhuayuan.uilibrary.banner.core.HiBannerMo
import org.wenhuayuan.uilibrary.banner.core.IHiBanner

class ProfileFragment : HiBaseFragment() {
    val itemSpace = "  "
    private var layout:View? = null
    private val REQUEST_CODE_LOGIN_PROFILE = 1001
    override fun getLayoutRes(): Int {
        return R.layout.fragment_profile
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        layout = view
        // 设置 底部 四个功能item 入口 图标文案


        item_course.setText(R.string.if_notify)
        item_course.append(itemSpace + getString(R.string.item_notify))

        item_collection.setText(R.string.if_collection)
        item_collection.append(itemSpace + getString(R.string.item_collection))

        item_address.setText(R.string.if_address)
        item_address.append(itemSpace + getString(R.string.item_address))

        item_history.setText(R.string.if_history)
        item_history.append(itemSpace + getString(R.string.item_history))

        item_playground.setOnClickListener {
            startActivity(Intent(context, DemoListActivity::class.java))
        }

        queryLoginUserData()
        queryCourseNotice()

    }

    private fun queryCourseNotice() {
        ApiFactory.create(AccountApi::class.java).notice().enqueue(object : HiCallback<CourseNotice>{
            override fun onSuccess(response: HiResponse<CourseNotice>) {
                if (response.data != null && response.data!!.total > 0) {
                    notify_count.text = response.data!!.total.toString()
                    notify_count.visibility = View.VISIBLE
                } else {
                    showToast("onSuccess@notice失败")
                }
            }

            override fun onFailed(throwable: Throwable) {
                showToast("onFailed@notice失败")
            }
        })
    }


    private fun queryLoginUserData() {
        ApiFactory.create(AccountApi::class.java).profile().enqueue(object : HiCallback<UserProfile>{
            override fun onSuccess(response: HiResponse<UserProfile>) {
                val userProfile = response.data
                if (null != userProfile && response.code == HiResponse.SUCCESS) {
                    updateUI(userProfile)
                } else {
                    Toast.makeText(this@ProfileFragment.activity, "onSuccess@失败", Toast.LENGTH_LONG).show()
                }
            }

            override fun onFailed(throwable: Throwable) {
                showToast("onFailed@登录失败")
            }
        })
    }

    private fun updateUI(userProfile: UserProfile) {
//        val avatar = layout!!.findViewById<ImageView>(R.id.user_avatar)
        user_avatar?.setImageResource(R.drawable.ic_avatar_default)
//        if (userProfile.isLogin) avatar?.loadUrl(userProfile.avatar) else avatar?.setImageResource(R.drawable.ic_avatar_default)
        user_name.setOnClickListener {
            Log.e("profile-fragment", "user_name.setOnClickListener" + ARouterPath.AROUTER_PATH_USER_LOGIN)
//            ARouter.getInstance().build(ARouterPath.AROUTER_PATH_USER_LOGIN).navigation(this@ProfileFragment.activity, REQUEST_CODE_LOGIN_PROFILE)
            goLogin()
        }

        user_name.text = if (userProfile.isLogin) userProfile.userName else getString(R.string.profile_not_login)
        login_desc.text = if (userProfile.isLogin) getString(R.string.profile_login_desc_welcome_back) else getString(R.string.profile_login_desc)

        tab_item_collection.text = spannableTabItem(userProfile.favoriteCount, getString(R.string.profile_tab_item_collection))
        tab_item_history.text = spannableTabItem(userProfile.browseCount, getString(R.string.profile_tab_item_history))
        tab_item_learn.text = spannableTabItem(userProfile.learnMinutes, getString(R.string.profile_tab_item_learn))

        updateBanner(userProfile.bannerNoticeList)
    }

    private fun goLogin() {
        startActivityForResult(Intent(activity, LoginActivity::class.java), REQUEST_CODE_LOGIN_PROFILE)
//        ARouter.getInstance().build(ARouterPath.AROUTER_PATH_USER_LOGIN).navigation(activity, REQUEST_CODE_LOGIN_PROFILE)
    }

    private fun updateBanner(bannerNoticeList: List<Notice>?) {
        bannerNoticeList?.apply {
            val modles = mutableListOf<HiBannerMo>()
            this.forEach {
               val hiBannerMo = object : HiBannerMo(){}
                hiBannerMo.url = it.cover
                modles.add(hiBannerMo)
            }
            hi_banner.setBannerData(R.layout.layout_list_item_banner, modles)
            hi_banner.setBindAdapter { viewHolder, mo, position ->
                viewHolder?.let { vh ->
                    val imageView = vh.findViewById<ImageView>(R.id.banner_item_imageview)
                    imageView?.loadCorner(mo.url, HiDisplayUtil.dp2px(10f, resources))
                }
            }
            hi_banner.setOnBannerClickListener(object: IHiBanner.OnBannerClickListener{
                override fun onBannerClick(
                    viewHolder: HiBannerAdapter.HiBannerViewHolder,
                    bannerMo: HiBannerMo,
                    position: Int
                ) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(bannerMo.url))
                    startActivity(intent)
                }

                override fun onBannerLongClick(
                    viewHolder: HiBannerAdapter.HiBannerViewHolder,
                    bannerMo: HiBannerMo,
                    position: Int
                ) {
                }
            })
            hi_banner.visibility = View.VISIBLE
        }
    }

    private fun spannableTabItem(topTxt: Int, bottomTxt: String): CharSequence? {
        val spanStr = topTxt.toString()
        val ssb = SpannableStringBuilder()
        val ssTop = SpannableString(spanStr)

        ssTop.setSpan(ForegroundColorSpan(resources.getColor(R.color.color_000)), 0, ssTop.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        ssTop.setSpan(AbsoluteSizeSpan(18, true), 0, ssTop.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        ssTop.setSpan(StyleSpan(Typeface.BOLD), 0, ssTop.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        ssb.append(ssTop)
        ssb.append(bottomTxt)
        return ssb
    }

    private fun showToast(msg: String?) {
        msg?.let {
            Toast.makeText(this@ProfileFragment.activity, msg, Toast.LENGTH_LONG).show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        data?.let {
            if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_LOGIN_PROFILE) {
                queryLoginUserData()
                queryCourseNotice()
            }
        }
    }
}